package com.cindata

import grails.gorm.transactions.Transactional
import net.sf.json.JSON
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.*
import grails.converters.JSON

@Transactional
@Secured(['isAuthenticated()'])
class RiskWarningConfigController {

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]
    
    def componentService
    def springSecurityService
    def riskWarningConfigService
    def dataSource
    
    def index(Integer max)
    {
        def user = User.findById(springSecurityService.principal.id)
        params.max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0
        def name = params['name']
        def status = params['status']
        def sql = " from RiskWarningConfig o where 1=1 and o.bankAccount.id = ${user?.account?.id} "
        if (name)
        {
            sql += " and o.name like '%${name}%'"
        }
        if (status) 
        {
            sql += " and o.status = ${status}"    
        }
        def countSql = " select count(o.id) " + sql
        sql += "order by o.modifiedDate desc "
        def riskWarningConfigList = RiskWarningConfig.executeQuery(sql, [max: params.max, offset: params.offset])
        def riskWarningConfigCount = RiskWarningConfig.executeQuery(countSql)
        respond riskWarningConfigList, model: [riskWarningConfigCount: riskWarningConfigCount[0], params: params]
    }

    def riskWarningConfig() 
    {
        respond new RiskWarningConfig(), model: [componentService: componentService]
    }

    def modifyValue(){
        def id = params['id']
        def minValue = params['minValue']
        def isAuto = params['isAuto']
        def duration = params['duration']
        def workflowId = params['workflow']
        def riskWarningConfig = RiskWarningConfig.findById(id)

        if (!riskWarningConfig)
        {
            render(["failed"] as JSON)
            return
        }
        def workflow = null
        if(workflowId){
            workflow = Workflow.findById(Long.parseLong(workflowId))
        }
        def code = riskWarningConfig?.code
        if(code == '1' || code == '2'|| code == '8'|| code == '9'){
            riskWarningConfig.minValue = new BigDecimal(minValue).divide(new BigDecimal("100"))
        }else{
            riskWarningConfig.minValue = new BigDecimal(minValue)
        }
        riskWarningConfig.isAuto = Boolean.parseBoolean(isAuto)
        riskWarningConfig.duration = duration
        riskWarningConfig.workflow = workflow
        riskWarningConfig.save(flush: true)
        redirect view: 'index'
    }

    def changeValue(){
        def id = params['id']
        def value = params['value']
        def isAuto = params['isAuto']
        def duration = params['duration']
        def workflowId = params['workflow']
        def riskWarningConfig = RiskWarningConfig.findById(id)

        if (!riskWarningConfig)
        {
            render(["failed"] as JSON)
            return
        }
        def workflow = null
        if(workflowId){
            workflow = Workflow.findById(Long.parseLong(workflowId))
        }

        riskWarningConfig.value = value
        riskWarningConfig.isAuto = Boolean.parseBoolean(isAuto)
        riskWarningConfig.duration = duration
        riskWarningConfig.workflow = workflow
        riskWarningConfig.save(flush: true)
        redirect view: 'index'
    }

    def show(RiskWarningConfig riskWarningConfig) {
        respond riskWarningConfig
    }

    def create() {
        respond new RiskWarningConfig(params)
    }

    @Transactional
    def save(RiskWarningConfig riskWarningConfig) 
    {
        println riskWarningConfig.errors
        if (riskWarningConfig == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }
        if (riskWarningConfig.hasErrors()) {
            transactionStatus.setRollbackOnly()
            respond riskWarningConfig.errors, view:'create'
            return
        }

        riskWarningConfig.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'riskWarningConfig.label', default: 'RiskWarningConfig'), riskWarningConfig.id])
                redirect riskWarningConfig
            }
            '*' { respond riskWarningConfig, [status: CREATED] }
        }
    }

    def edit(RiskWarningConfig riskWarningConfig) {
        respond riskWarningConfig
    }

    @Transactional
    def update(RiskWarningConfig riskWarningConfig) 
    {
        println riskWarningConfig?.errors
        if (riskWarningConfig == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (riskWarningConfig.hasErrors()) {
            transactionStatus.setRollbackOnly()
            respond riskWarningConfig.errors, view:'edit'
            return
        }

        if (riskWarningConfig.status == 1 && !RiskWarningConfigRule.findByRiskWarningConfig(riskWarningConfig)) 
        {
            flash.message = "请先添加等级规后再启用！"
            transactionStatus.setRollbackOnly()
            respond riskWarningConfig.errors, view:'edit'
            return
        }

        riskWarningConfig.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'riskWarningConfig.label', default: 'RiskWarningConfig'), riskWarningConfig.id])
                redirect riskWarningConfig
            }
            '*'{ respond riskWarningConfig, [status: OK] }
        }
    }

    @Transactional
    def delete(RiskWarningConfig riskWarningConfig) {

        if (riskWarningConfig == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        riskWarningConfig.delete flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'riskWarningConfig.label', default: 'RiskWarningConfig'), riskWarningConfig.id])
                redirect action:"index", method:"GET"
            }
            '*'{ render status: NO_CONTENT }
        }
    }

    protected void notFound() {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'riskWarningConfig.label', default: 'RiskWarningConfig'), params.id])
                redirect action: "index", method: "GET"
            }
            '*'{ render status: NOT_FOUND }
        }
    }

    def executeWarningConfig(RiskWarningConfig riskWarningConfig)
    {
        def targetUri = request.getHeader("referer")
        def sourceClassType = riskWarningConfig.sourceClassType
        if (sourceClassType == '押品') 
        {
            riskWarningConfigService.executeCollateral(riskWarningConfig)
        }
        if (sourceClassType == '贷款') 
        {
            riskWarningConfigService.executeMortgage(riskWarningConfig)
        }
        if (sourceClassType == '借款人') 
        {
            riskWarningConfigService.executeContact(riskWarningConfig)
        }
        if (sourceClassType == '小区') 
        {
            riskWarningConfigService.executeCommunity(riskWarningConfig)
        }
        if (sourceClassType == '机构') 
        {
            riskWarningConfigService.executeAccount(riskWarningConfig)
        }

        redirect url: targetUri
    }

    def warningConfigList()
    {
        def user = User.findById(springSecurityService.principal.id)
        def result = RiskWarningConfig.findAllByChartStatusAndBankAccount(1, user?.account)
        render([result: result] as JSON)
    }

    def getChartData(RiskWarningConfig riskWarningConfig)
    {
        def result = []
        def user = User.findById(springSecurityService.principal.id)
        def accountList = Account.FilterAccountSql(user)
        def chartSql = riskWarningConfig?.chartSql
        if (chartSql) 
        {
            chartSql = chartSql?.replace('$accountSql', accountList)
            // chartSql = chartSql?.replace('$warningConfig', riskWarningConfig?.id?.toString())
            chartSql = chartSql?.replace('$warningType', riskWarningConfig?.warningType?.id?.toString())
            def db = new groovy.sql.Sql(dataSource)
            try 
            {
                result = db.rows(chartSql).asList()
            }
            catch(Exception e) 
            {
                e.printStackTrace()
            }
            finally 
            {
                db.close()
            }
        }
        println result
        render([result: result] as JSON)
    }
}
